<?php

namespace app\admin\model;

use app\api\help\SendMsg;
use app\api\model\MallTradeRecordLog;
use app\api\model\MallUser;
use app\common\model\TimeModel;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;
use Yansongda\Pay\Pay;

class MallOrder extends TimeModel
{
    
    protected $name = "mall_order";
    
    protected $deleteTime = "delete_time";
    
    protected $payTime = "pay_time";
    
    public function goods()
    {
        return $this->hasOne('app\admin\model\MallGoods', 'id', 'goods_id');
    }
    public function user()
    {
        return $this->hasOne('app\admin\model\MallUser', 'id', 'user_id');
    }
    public function collage()
    {
        return $this->hasOne('app\admin\model\MallCollage', 'collage_id', 'collage_id');
    }
    public static function fullCollage($post)
    {
        if (empty($post[ 'collage_id' ])) {
            return ['status' => 0, 'msg' => '商品不能为空'];
        }
        $collage = MallCollage::where([['collage_id', '=', $post[ 'collage_id' ]]])->find()->toArray();
        if (empty($collage)) {
            return ['status' => 0, 'msg' => '拼团不存在'];
        }
        $goods = MallGoods::find($collage[ 'goods_id' ])->toArray();
        if (empty($goods)) {
            return ['status' => 0, 'msg' => '商品不存在'];
        }
        $num = (int) $post[ 'person_number' ] ?? 0;
        if ($num < 1) {
            return ['status' => 0, 'msg' => '虚拟人数至少为1'];
        }
        if ($num + $collage[ 'join_num' ] > $collage[ 'collage_num' ]) {
            return ['status' => 0, 'msg' => '该商品为' . $collage[ 'collage_num' ] . '人团，请输入少于等于' . ((int) $collage[ 'collage_num' ] - (int) $collage[ 'join_num' ]) . '个虚拟人数'];
        }
        $virtualPerson = MallUser::where([['is_virtual', '=', 1]])->limit($num)->select()->toArray();
        try {
            //开启事务
            Db::startTrans();
            $specIds      = array_column($goods, 'spec_id');
            $specs        = MallGoodsSpec::where([['spec_id', 'in', $specIds]])->select()->toArray();
            $specs        = array_column($specs, null, 'spec_id');
            $orderAddData = [];
            foreach ($virtualPerson as $val) {
                $orderAddData[] = [
                    'order_no'        => createOrderNo(),
                    'user_id'         => $val[ 'id' ],
                    'goods_id'        => $goods[ 'id' ],
                    'goods_name'      => $goods[ 'title' ],
                    'spec_id'         => $goods[ 'spec_id' ],
                    'spec_name'       => $specs[ $goods[ 'spec_id' ] ][ 'name' ] ?? '',
                    'total_price'     => $goods[ 'market_price' ],
                    'order_price'     => $goods[ 'discount_price' ],
                    'pay_price'       => $goods[ 'discount_price' ],
                    'pay_balance'     => 0,
                    'pay_time'        => time(),
                    'failure_subsidy' => $goods[ 'failure_reward' ],
                    'order_status'    => 10,
                    'collage_id'      => $post[ 'collage_id' ],
                    'is_virtual'      => 1,
                    'create_time'     => time(),
                    'update_time'     => time(),
                ];
            }
            if (false === MallOrder::insertAll($orderAddData)) {
                _throwNewException('添加拼团订单错误');
            }
            //如果新加人数和原有人数正好等于拼团人数
            if ($num + $collage[ 'join_num' ] == $collage[ 'collage_num' ]) {
                //修改订单状态为拼团成功
                if (false === MallOrder::where([['collage_id', '=', $post[ 'collage_id' ]], ['order_status', '=', 10]])->update(['order_status' => 30, 'collage_status' => 2, 'update_time' => time()])) {
                    _throwNewException('添加拼团订单错误');
                }
                //修改拼团状态为拼团成功
                if (false === MallCollage::where([['collage_id', '=', $post[ 'collage_id' ]]])->update(['finish_time' => time(), 'update_time' => time()])) {
                    _throwNewException('添加拼团订单错误');
                }
            }
            //修改拼团人数
            if (false === MallCollage::where([['collage_id', '=', $post[ 'collage_id' ]]])->update(['join_num' => $num + $collage[ 'join_num' ] - 1])) {
                _throwNewException('添加拼团订单错误');
            }
            Db::commit();
            return ['status' => 1, 'msg' => '成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['status' => 0, 'msg' => '保存失败:' . $e->getMessage()];
        }
    }
    
    public static function createNewCollage($post)
    {
        if (empty($post[ 'goods_id' ])) {
            return ['status' => 0, 'msg' => '商品不能为空'];
        }
        $goods = MallGoods::find($post[ 'goods_id' ])->toArray();
        if (empty($goods)) {
            return ['status' => 0, 'msg' => '商品不存在'];
        }
        $num = $post[ 'person_number' ];
        if ($num < 1) {
            return ['status' => 0, 'msg' => '虚拟人数至少为1'];
        }
        if ($num >= $goods[ 'collage_num' ]) {
            return ['status' => 0, 'msg' => '该商品为' . $goods[ 'collage_num' ] . '人团，请输入少于' . $goods[ 'collage_num' ] . '个虚拟人数'];
        }
        $virtualPerson = MallUser::where([['is_virtual', '=', 1]])->orderRaw('rand()')->limit(1)->select()->toArray();
        try {
            //开启事务
            Db::startTrans();
            $collageAddData = [
                'goods_id'       => $goods[ 'id' ],
                'user_id'        => $virtualPerson[ 0 ][ 'id' ],
                'collage_no'     => createCollageNo(),
                'join_num'       => $num,
                'start_time'     => time(),
                'end_time'       => time() + $goods[ 'day_num' ] * 3600 * 24,
                'failure_reward' => $goods[ 'failure_reward' ],
                'collage_num'    => $goods[ 'collage_num' ],
                'create_time'    => time(),
                'update_time'    => time(),
            ];
            $collageId      = MallCollage::insertGetId($collageAddData);
            if (false === $collageId) {
                _throwNewException('添加拼团错误');
            }
            $specIds      = array_column($goods, 'spec_id');
            $specs        = MallGoodsSpec::where([['spec_id', 'in', $specIds]])->select()->toArray();
            $specs        = array_column($specs, null, 'spec_id');
            $orderAddData = [];
            foreach ($virtualPerson as $val) {
                $orderAddData[] = [
                    'order_no'        => createOrderNo(),
                    'user_id'         => $val[ 'id' ],
                    'goods_id'        => $goods[ 'id' ],
                    'goods_name'      => $goods[ 'title' ],
                    'spec_id'         => $goods[ 'spec_id' ],
                    'spec_name'       => $specs[ $goods[ 'spec_id' ] ][ 'name' ] ?? '',
                    'total_price'     => $goods[ 'market_price' ],
                    'order_price'     => $goods[ 'discount_price' ],
                    'pay_price'       => $goods[ 'discount_price' ],
                    'pay_balance'     => 0,
                    'pay_time'        => time(),
                    'failure_subsidy' => $goods[ 'failure_reward' ],
                    'order_status'    => 10,
                    'collage_id'      => $collageId,
                    'is_virtual'      => 1,
                    'create_time'     => time(),
                    'update_time'     => time(),
                ];
            }
            if (false === MallOrder::insertAll($orderAddData)) {
                _throwNewException('添加拼团订单错误');
            }
            Db::commit();
            return ['status' => 1, 'msg' => '成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['status' => 0, 'msg' => '保存失败:' . $e->getMessage()];
        }
    }
    /**
     * 退款处理
     * @param $payData
     * @return array
     * @throws \Yansongda\Pay\Exception\ContainerException
     * @throws \Yansongda\Pay\Exception\InvalidParamsException
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
     */
    public static function orderRefundInfo($payData)
    : array
    {
        if ( !is_array($payData)) {
            
            $payData = $payData->toArray();
        }
        $config = Config::get('payConfig');
        $order  = [
            'out_trade_no'  => $payData[ 'order_no' ],
            'out_refund_no' => $payData[ 'order_no' ],
            'amount'        => [
                'refund'   => $payData[ 'pay_price' ],
                'total'    => $payData[ 'pay_price' ],
                'currency' => 'CNY',
            ],
            'notify_url'    => 'https://tg.aipintuangou.com/api/order/refundNotify',
        ];
        $wechat = Pay::wechat($config)->refund($order);
        $res    = $wechat->toArray();
        Log::write($res);
        return $res;
    }
    
    /**
     * @param $order
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function resolveCollage($order)
    {
        if ($order[ 'collage_id' ] != $order[ 'u_collage_id' ] && $order[ 'u_collage_id' ] > 0) {
            $joinNum = MallCollage::where('collage_id', $order[ 'u_collage_id' ])->value('join_num');
            $finish  = MallCollage::where('collage_id', $order[ 'u_collage_id' ])->value('finish_time');
            //如果拼团人数大于0则减一
            if ($joinNum > 0 && $finish == null) {
                if (false === MallCollage::where('collage_id', $order[ 'u_collage_id' ])->update(['join_num' => ($joinNum - 1)])) {
                    _throwNewException('订单支付失败');
                }
            }
        }
    }
    /**
     * 添加失败奖励
     * @param $failure_reward
     * @param $userId
     * @param $orderId
     * @throws \think\Exception
     */
    public static function resolveFailureReward($failure_reward, $userId, $orderId, $collageId)
    {
        //查询拼团人数
        $joinNum        = MallCollage::where('collage_id', $collageId)->value('join_num');
        $failure_reward = $failure_reward * $joinNum;
        //添加失败奖励
        if ($failure_reward > 0) {
            $balance = MallUser::where('id', $userId)->value('balance');
            if (false === MallUser::where([['id', '=', $userId]])->update(['balance' => $balance + $failure_reward])) {
                _throwNewException('增加失败补助失败');
            }
            $modOrder = ['failure_subsidy' => $failure_reward];
            if (false === MallOrder::where('id', $orderId)->update($modOrder)) {
                _throwNewException('增加失败补助失败');
            }
            //添加交易记录
            $tradeLogData = [
                'trade_type'  => 3,
                'amount'      => $failure_reward,
                'balance'     => $balance + $failure_reward,
                'order_id'    => $orderId,
                'user_id'     => $userId,
                'create_time' => time(),
                'update_time' => time(),
            ];
            if (false === MallTradeRecordLog::insert($tradeLogData)) {
                _throwNewException('增加失败补助失败');
                
            }
        }
        
        $code = 'SMS_460900206';
        if ( !empty($code)) {
            $mobile = MallUser::where('id', $userId)->value('mobile');
            $msg    = [];
            SendMsg::sendMsg($mobile, $msg, $code);
        }
    }
    /**
     * 成功奖励退回
     * @param $order
     */
    public static function resolveRefundSuccessReward($order)
    {
        if ($order[ 'success_reward' ] > 0) {
            $balance = MallUser::where('id', $order[ 'user_id' ])->value('balance');
            if (false === MallUser::where([['id', '=', $order[ 'user_id' ]]])->update(['balance' => $balance - $order[ 'success_reward' ]])) {
                _throwNewException('增加失败补助失败');
            }
            $modOrder = ['success_reward' => 0];
            if (false === MallOrder::where('id', $order[ 'id' ])->update($modOrder)) {
                _throwNewException('增加失败补助失败');
            }
            //添加交易记录
            MallTradeRecordLog::addRecord($order[ 'user_id' ], $order[ 'id' ], $order[ 'success_reward' ], $balance - $order[ 'success_reward' ], 4);
        }
    }
}